<template>
  <div style="margin-top:30px">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item  label="客户" prop="shipmentCode">
              <shipmentSelect ref="shipmentSelect"  @setCustomerCode="setCustomerCode" style="width: 100%"/>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="remarks" style="margin-right:15px">
              <el-input v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="合同名称" prop="name" style="margin-right:15px">
              <el-input v-model="form.name" placeholder="请输入合同名称" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="有效期" prop="validityDate" min-width="350"  style="margin-right:15px">
              <el-date-picker
                v-model="form.validityDate"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"

                type="daterange"
                style="width:100%"
            range-separator="至"

                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-form-item label="附件地址" prop="contractPath">
              <el-upload
                ref="upload"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUploadFile"
                :on-error="handleError"
                :auto-upload="true"

                :on-success="handleAvatarSuccess"
                :file-list="fileList"
                :headers="getAuthorization()"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传1个文件，且不超过10M</div>
              </el-upload>
              <el-input v-model="form.fileName" type="hidden" />
              <el-input v-model="form.contractPath" type="hidden" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="funcCancel">取 消</el-button>
      <el-button type="primary" @click="funcSubmit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import request from '@/utils/request'
import shipmentSelect from '@/views/components/shipmentSelect.vue'

Vue.use(VXETable)
export default {
  name: 'ContractAdd',
  components:{
    shipmentSelect
  },
  data() {
    return {
      uploadUrl: this.BASE_API_URL + "ntocc-tps-api/fileUpload",
      uploadComplete:true,
      validityDate:'',
      form: {
        code: '',
        shipmentCode: '',
        shipmentName:'',
        name: '',
        remarks:'',
        contractPath: '',
        fileName:'',
        startDate: '',
        validityDate:'',
        endDate: ''
      },
      fileList: [],
      files: [],
      partys:[],
      rules: {
        code: [
          { required: true, message: '请输入预约入库单号', trigger: 'blur' },

        ],
        shipmentCode: [
          { required: true, message: '请输入客户姓名', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入合同名称', trigger: 'blur' },

        ],
        contractPath: [
          { required: true, message: '请上传正确的附件', trigger: 'blur' }
        ],
        validityDate: [
            { required: true, message: '请输入有效期', trigger: 'blur' }
        ]
      },
        //时间区间
        pickerOptions: {
            shortcuts: [
                {
                    text: '未来一周',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
                        picker.$emit('pick', [start, end])
                    }
                },
                {
                    text: '未来一个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
                        picker.$emit('pick', [start, end])
                    }
                },
                {
                    text: '未来三个月',
                    onClick(picker) {
                        const end = new Date()
                        const start = new Date()
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
                        picker.$emit('pick', [start, end])
                    }
                }
            ]
        }

    }
  },
  created() {
  },
  methods: {

      //初始化页面，去除上次缓存数据及验证信息等
      init(){
        this.$refs['form'].resetFields()
        this.$refs.shipmentSelect.setSelectValue('')
        this.$refs.upload.clearFiles()
      },
      //上传前校验
      beforeUploadFile(file) {
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024

        // if(extension !== 'xls') {
        //   this.$message.error("只能上传xls,xlsx的文件")
        // }
        if(size > 10) {
          this.$message.error('上传文件大小不能超过 10MB!')
            return false;
        }
        this.uploadComplete=false;
      },

      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },

    handleUpload(raw) {
      this.files.push(raw.file);
    },
    // 选择客户
    setCustomerCode(value) {
      this.form.shipmentName = value.name
      this.form.shipmentCode = value;
      this.tableData = [];
    },

    handleRemove(file, fileList) {
        if(fileList.length<1){
            this.form.contractPath='';
        }
    },
    handlePreview(file) {
      // console.log(file)
    },
    handleAvatarSuccess(response, file, fileList) {
      // console.log(file)
      this.$message({ message: response.msg, type: 'success' });
      this.form.contractPath = response.data;
      this.form.fileName = file.name;
      this.uploadComplete=true;
      this.$refs['form'].validateField('contractPath');
      // console.log(fileList)
    },
      // 文件上传失败时的钩子
      handleError(err, file, fileList) {
        this.$notify.error({
          title: '错误',
          message: `文件上传失败`
        });
        this.uploadComplete=true;
      },

    uploadFile:function(file){
        this.fileData.append('file', file.file);
    },
    // 提交
    funcSubmit() {
      if(!this.uploadComplete){
          this.$message({ message: '请先等待上传完成再提交', type: 'error' })
          return false;
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.startDate = this.form.validityDate[0];
          this.form.endDate = this.form.validityDate[1];
          const data = this.form;
          request({ url: '/ntocc-wms-api/contract', method: 'post', params: data }).then(response => {
            this.$message({ message: response.msg, type: 'success' })
            this.$refs.upload.submit();
            this.$emit('fatherAddMethod')
          }).then(() =>{
              this.$refs['form'].resetFields()
              this.$refs.shipmentSelect.setSelectValue('')
              this.$refs.upload.clearFiles()
            })
        } else {
          return false
        }
      })
    },

    // 取消
    funcCancel() {
      this.$emit('fatherCancelMethod', 'add')
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
<style lang="scss" scoped>
    .dialog-footer {
        margin:15px 0 15px 0;
        width: 175px;
        float: right;
    }
</style>
